import React, { useState, useEffect } from 'react';
import { Link } from 'react-router-dom';
import { getLeaderboard } from '../utils/voteApi';
import type { LeaderboardPeriod } from '../types/vote';
import ThemeToggle from '../components/ui/ThemeToggle';
import MagnifierTooltip from '../components/ui/MagnifierTooltip';

// 排行榜卡片展示所需的最小信息（作品榜）
interface LeaderboardRow {
  id: number;
  title: string;
  imageData: string;
  drawingType: 'bird' | 'fish' | 'boat';
  user: { id: number; username: string; email?: string };
  createdAt: string;
  voteCount: number;
}

// 作者榜条目
interface AuthorRow {
  user: { id: number; username: string; email?: string };
  totalVotes: number;
  worksCount: number;
  topDrawing?: { id: number; title: string; imageData: string; voteCount: number };
}

const LeaderboardPage: React.FC = () => {
  const [boardType, setBoardType] = useState<'drawing' | 'author'>('drawing');
  const [period, setPeriod] = useState<LeaderboardPeriod>('weekly');
  const [leaderboardItems, setLeaderboardItems] = useState<LeaderboardRow[]>([]);
  const [authorItems, setAuthorItems] = useState<AuthorRow[]>([]);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);
  const [currentPage, setCurrentPage] = useState(1);
  const [itemsPerPage] = useState(10); // 每页显示10项

  useEffect(() => {
    const fetchLeaderboard = async () => {
      try {
        setLoading(true);
        setError(null);

        // 计算时间窗口（recent N 天）；all 表示不限制
        const now = new Date();
        const periodDays = period === 'daily' ? 1 : period === 'weekly' ? 7 : period === 'monthly' ? 30 : 0; // all -> 0 表示不限制
        const startTime = new Date(now.getTime() - periodDays * 24 * 60 * 60 * 1000);

        // 拉取投票记录（已包含 drawing 与 user 的 normalize）
        const votesResp = await getLeaderboard(period);
        const votes = (votesResp as any).data || [];

        // 作品榜聚合：统计时间窗口内、公开画作的票数
        const drawingCounter = new Map<number, { count: number; drawing: any }>();

        // 作者榜聚合：作者总票数 + 各作品票数（用于找出 top 作品）
        const authorCounter = new Map<number, { user: any; total: number; drawings: Map<number, { count: number; drawing: any }> }>();

        for (const v of votes) {
          const created = new Date(v.createdAt);
          if (period !== 'all' && created < startTime) continue;
          const d = v.drawing;
          const u = v.user;
          if (!d || !u) continue;
          if (!d.isPublic) continue;

          // 作品榜计数
          const dKey = d.id;
          if (!drawingCounter.has(dKey)) drawingCounter.set(dKey, { count: 0, drawing: d });
          drawingCounter.get(dKey)!.count += 1;

          // 作者榜计数
          const uKey = u.id;
          if (!authorCounter.has(uKey)) {
            authorCounter.set(uKey, { user: u, total: 0, drawings: new Map() });
          }
          const a = authorCounter.get(uKey)!;
          a.total += 1;
          if (!a.drawings.has(dKey)) a.drawings.set(dKey, { count: 0, drawing: d });
          a.drawings.get(dKey)!.count += 1;
        }

        // 作品榜数据
        const rows: LeaderboardRow[] = Array.from(drawingCounter.values())
          .map(({ count, drawing }) => ({
            id: drawing.id,
            title: drawing.title || '未命名作品',
            imageData: drawing.imageData,
            drawingType: drawing.drawingType,
            user: drawing.user || { id: 0, username: '匿名用户' },
            createdAt: drawing.createdAt,
            voteCount: count,
          }))
          .sort((a, b) => b.voteCount - a.voteCount);

        setLeaderboardItems(rows);
        setCurrentPage(1); // Reset to first page on new data

        // 作者榜数据
        const authors: AuthorRow[] = Array.from(authorCounter.values())
          .map(({ user, total, drawings }) => {
            let top: { id: number; title: string; imageData: string; voteCount: number } | undefined = undefined;
            for (const { count, drawing } of drawings.values()) {
              if (!top || count > top.voteCount) {
                top = { id: drawing.id, title: drawing.title || '未命名作品', imageData: drawing.imageData, voteCount: count };
              }
            }
            return {
              user: { id: user.id, username: user.username, email: user.email },
              totalVotes: total,
              worksCount: drawings.size,
              topDrawing: top,
            } as AuthorRow;
          })
          .sort((a, b) => b.totalVotes - a.totalVotes);

        setAuthorItems(authors);
        setCurrentPage(1); // Reset to first page on new data
      } catch (error) {
        console.error('Error fetching leaderboard:', error);
        if (error instanceof Error) {
          if (error.message.includes('服务器连接失败')) {
            setError('无法连接到服务器，请检查网络连接或联系管理员');
          } else if (error.message.includes('服务器错误')) {
            setError('服务器暂时不可用，请稍后重试');
          } else {
            setError(`获取排行榜数据失败：${error.message}`);
          }
        } else {
          setError('获取排行榜数据失败，请重试');
        }
      } finally {
        setLoading(false);
      }
    };

    fetchLeaderboard();
  }, [period]);

  return (
    <div className="min-h-screen bg-base-100">
      <header className="bg-base-200 shadow-md">
        <div className="container mx-auto px-4 py-3">
          <div className="flex items-center justify-between">
            <div className="flex items-center gap-3">
              <Link to="/" className="flex items-center gap-2">
                <img src="/logo.svg" alt="海天摸鱼" className="w-8 h-8" />
-                <h1 className="text-xl font-bold text-primary">海天摸鱼</h1>
+                <h1 className="text-xl font-bold text-base-content site-title">海天摸鱼</h1>
              </Link>
            </div>
            <div className="flex items-center gap-4">
              <ThemeToggle />
              <Link to="/" className="btn btn-ghost btn-sm">
                返回首页
              </Link>
            </div>
          </div>
        </div>
      </header>

      <main className="container mx-auto px-4 py-8">
        <div className="flex flex-col items-center mb-8 w-full">

          {/* 榜单类型 */}
          <div className="tabs tabs-boxed mb-3 bg-base-200 rounded-box p-1">
            <button
              className={`tab ${boardType === 'drawing' ? 'tab-active' : ''}`}
              onClick={() => setBoardType('drawing')}
            >
              作品榜
            </button>
            <button
              className={`tab ${boardType === 'author' ? 'tab-active' : ''}`}
              onClick={() => setBoardType('author')}
            >
              作者榜
            </button>
          </div>

          {/* 时间段 */}
          <div className="tabs tabs-boxed bg-base-200 rounded-box p-1">
            <button 
              className={`tab ${period === 'daily' ? 'tab-active' : ''}`}
              onClick={() => setPeriod('daily')}
            >
              日榜
            </button>
            <button 
              className={`tab ${period === 'weekly' ? 'tab-active' : ''}`}
              onClick={() => setPeriod('weekly')}
            >
              周榜
            </button>
            <button 
              className={`tab ${period === 'monthly' ? 'tab-active' : ''}`}
              onClick={() => setPeriod('monthly')}
            >
              月榜
            </button>
            <button 
              className={`tab ${period === 'all' ? 'tab-active' : ''}`}
              onClick={() => setPeriod('all')}
            >
              总榜
            </button>
          </div>
        </div>

        {loading ? (
          <div className="flex justify-center py-12">
            <span className="loading loading-spinner loading-lg"></span>
          </div>
        ) : error ? (
          <div className="alert alert-error">
            <svg className="w-6 h-6 mr-2" fill="none" stroke="currentColor" viewBox="0 0 24 24">
              <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M12 9v2m0 4h.01m-6.938 4h13.856c1.54 0 2.502-1.667 1.732-3L13.732 4c-.77-1.333-2.694-1.333-3.464 0L3.34 16c-.77 1.333.192 3 1.732 3z" />
            </svg>
            <span>{error}</span>
          </div>
        ) : boardType === 'drawing' ? (
          leaderboardItems.length === 0 ? (
            <>
               <div className="text-center py-12">
                 <p className="text-lg text-base-content/70">暂无排行数据</p>
               </div>
               <div className="flex justify-center mt-4">
             <div className="join">
               {Array.from({ length: Math.ceil(leaderboardItems.length / itemsPerPage) }, (_, i) => (
                 <button
                   key={i}
                   className={`join-item btn ${currentPage === i + 1 ? 'btn-active' : ''}`}
                   onClick={() => setCurrentPage(i + 1)}
                 >
                   {i + 1}
                 </button>
               ))}
             </div>
           </div>
            </>)
            : (
            <div className="overflow-x-auto">
             <table className="table table-zebra">
               <thead>
                 <tr>
                   <th className="text-center">排名</th>
                   <th className="text-left">作品</th>
                   <th className="text-center">作者</th>
                   <th className="text-center">类型</th>
                   <th className="text-center">票数</th>
                 </tr>
               </thead>
               <tbody>
                 {leaderboardItems.slice((currentPage - 1) * itemsPerPage, currentPage * itemsPerPage).map((item, index) => (
                   <tr key={item.id}>
                     <th className="text-center">
                       {index === 0 && <span className="text-3xl">🥇</span>}
                       {index === 1 && <span className="text-3xl">🥈</span>}
                       {index === 2 && <span className="text-3xl">🥉</span>}
                       {index > 2 && index + 1}
                     </th>
                     <td className="text-left">
                       <div className="flex items-center gap-3">
                         <MagnifierTooltip 
                           title={item.title}
                           imageUrl={item.imageData}
                         >
                           <div className="avatar cursor-pointer">
                             <div className="mask mask-squircle h-24 w-24 group bg-white/90 p-1">
                               <img 
                                 src={item.imageData} 
                                 alt={item.title} 
                                 className="group-hover:scale-110 transition-transform duration-300 rounded-lg"
                               />
                             </div>
                           </div>
                         </MagnifierTooltip>
                         <div>
                           <div className="font-bold">{item.title}</div>
                         </div>
                       </div>
                     </td>
                     <td className="text-center">{item.user?.username || '匿名用户'}</td>
                     <td className="text-center">{item.drawingType}</td>
                     <td className="text-center">{item.voteCount}</td>
                   </tr>
                 ))}
               </tbody>
             </table>
           </div>
          )
        ) : (
           // 作者榜
           authorItems.length === 0 ? (
             <>
               <div className="text-center py-12">
                 <p className="text-lg text-base-content/70">暂无排行数据</p>
               </div>
               <div className="flex justify-center mt-4">
               <div className="join">
                 {Array.from({ length: Math.ceil(authorItems.length / itemsPerPage) }, (_, i) => (
                   <button
                     key={i}
                     className={`join-item btn ${currentPage === i + 1 ? 'btn-active' : ''}`}
                     onClick={() => setCurrentPage(i + 1)}
                   >
                     {i + 1}
                   </button>
                 ))}
               </div>
             </div>
            </>)
            : (
             <div className="overflow-x-auto">
               <table className="table table-zebra">
                 <thead>
                   <tr>
                     <th className="text-center">排名</th>
                     <th className="text-left">作者</th>
                     <th className="text-center">总票数</th>
                     <th className="text-center">作品数</th>
                     <th className="text-center">代表作</th>
                   </tr>
                 </thead>
                 <tbody>
                   {authorItems.slice((currentPage - 1) * itemsPerPage, currentPage * itemsPerPage).map((item, index) => (
                     <tr key={item.user.id}>
                       <th className="text-center">
                         {index === 0 && <span className="text-3xl">🥇</span>}
                         {index === 1 && <span className="text-3xl">🥈</span>}
                         {index === 2 && <span className="text-3xl">🥉</span>}
                         {index > 2 && index + 1}
                       </th>
                       <td className="text-left">
                         <div className="font-bold">{item.user.username}</div>
                       </td>
                       <td className="text-center">{item.totalVotes}</td>
                       <td className="text-center">{item.worksCount}</td>
                       <td className="text-center">
                         {item.topDrawing ? (
                           <div className="flex items-center justify-center gap-2">
                             <span>{item.topDrawing.title} ({item.topDrawing.voteCount} 票)</span>
                             <MagnifierTooltip 
                               title={item.topDrawing.title}
                               imageUrl={item.topDrawing.imageData}
                             >
                               <div className="avatar cursor-pointer">
                                 <div className="mask mask-squircle h-16 w-16 group bg-white/90 p-1">
                                   <img 
                                     src={item.topDrawing.imageData} 
                                     alt={item.topDrawing.title} 
                                     className="group-hover:scale-110 transition-transform duration-300 rounded-lg"
                                   />
                                 </div>
                               </div>
                             </MagnifierTooltip>
                           </div>
                         ) : (
                           '无'
                         )}
                       </td>
                     </tr>
                   ))}
                 </tbody>
               </table>
             </div>
           )
        )}
      </main>
    </div>
  );
};

export default LeaderboardPage;